package com.common.library.util;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.SystemClock;

import com.zs4sdk.common.Extra;
import com.zs4sdk.entity.Zs4GameData;

public class ParamsHelper {

    private static final String TAG = ParamsHelper.class.getSimpleName();

    private static String sUserAgent1;

    /**
     * 删除user_agent1
     */
    public static void deleteUserAgent1() {
        sUserAgent1 = null;
    }

    /**
     * 取得user_agent1
     *
     * @return
     */
    public static String getUserAgent1() {
        ConnectivityManager connectionManager = (ConnectivityManager) ActivityHelper.getGlobalApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
        String timestamp = getTimestamp();
        StringBuilder sb = new StringBuilder()
                .append("sid=").append(getDeviceId())
                .append("&sid2=").append(getDeviceID2())
                .append("&dt=50")
                .append("&mtype=").append(Build.MANUFACTURER)
                .append("&lang=").append(ProjectHelper.getLangString())
                .append("&net=").append(null != networkInfo ? "wifi".equalsIgnoreCase(networkInfo.getTypeName()) ? "1" : "2" : "")
                .append("&mac=").append(ActivityHelper.getMacAddress())
                .append("&osver=").append(Build.VERSION.RELEASE)
                .append("&sdk_ver=").append(Extra.VERSION)
                .append("&adtid=").append(getDeviceId())
                .append("&token=").append("")
                .append("&openid=").append(getDeviceId())
                .append("&app_id=").append(Zs4GameData.getInstance().getAppId())
                .append("&pt=11")
                .append("&channel=").append(Helper.isNull(Zs4GameData.getInstance().getChannel()) ? "" : Zs4GameData.getInstance().getChannel())
                .append("&ver=").append(ActivityHelper.getCurrentVersionName())
                .append("&uno=").append("")
                .append("&user_id=").append(Helper.isNull(Zs4GameData.getInstance().getUserId()) ? "" : Zs4GameData.getInstance().getUserId())
                .append("&loginkey=").append(Helper.isNull(Zs4GameData.getInstance().getLoginKey()) ? "" : Zs4GameData.getInstance().getLoginKey())
                .append("&nickname=").append(Helper.isNull(Zs4GameData.getInstance().getNickName()) ? "" : Zs4GameData.getInstance().getNickName())
                .append("&login_name=").append(Helper.isNull(Zs4GameData.getInstance().getLoginName()) ? "" : Zs4GameData.getInstance().getLoginName())
                .append("&mobile=").append(Helper.isNull(Zs4GameData.getInstance().getUserMobile()) ? "" : Zs4GameData.getInstance().getUserMobile())
                .append("&mode=").append(Helper.isNull(Zs4GameData.getInstance().getLoginType()) ? "" : Zs4GameData.getInstance().getLoginType())
                .append("&isbbsbind=").append("")
                .append("&usertoken=").append(Helper.isNull(Zs4GameData.getInstance().getToken()) ? "" : Zs4GameData.getInstance().getToken())
                .append("&sd=").append(MD5.md5(getPhoneStartTime()))
                .append("&sq=").append(getUUID())
                .append("&bssid=").append(getWifiMacAddress())
                .append("&lbssid=").append(getLastWifiMacAddress())
//                .append("&md5=").append(getMD5Code())
                .append("&role_id=").append(Helper.isNull(Zs4GameData.getInstance().getPlayerId()) ? "" : Zs4GameData.getInstance().getPlayerId())
                .append("&role_name=").append(Helper.isNull(Zs4GameData.getInstance().getPlayerName()) ? "" : Zs4GameData.getInstance().getPlayerName())
                .append("&role_level=").append(Helper.isNull(Zs4GameData.getInstance().getPlayerLevel()) ? "" : Zs4GameData.getInstance().getPlayerLevel())
                .append("&area_server_id=").append(Helper.isNull(Zs4GameData.getInstance().getServId()) ? "" : Zs4GameData.getInstance().getServId())
                .append("&area_server_name=").append(Helper.isNull(Zs4GameData.getInstance().getServName()) ? "" : Zs4GameData.getInstance().getServName())
                .append("&company=").append(Zs4GameData.getInstance().getCompany())
                .append("&system=").append("Android")
                .append("&timestamp=").append(timestamp)
                .append("&safety=").append(MD5.md5(Zs4GameData.getInstance().getAppId()
                        + Zs4GameData.getInstance().getChannel() + ActivityHelper.getMacAddress() + getDeviceId() + timestamp + Zs4GameData.getInstance().getAppKey()));;
//		LogUtil.i(TAG, "getUserAgent1: " + sb.toString());
        sUserAgent1 = JsonHelper.simpleEncode(sb.toString());
        return sUserAgent1;
    }



    public  static  String getsUserAgentForWeb(){
        StringBuilder sb = new StringBuilder()
                .append("&role_level=").append(Helper.isNull(Zs4GameData.getInstance().getPlayerLevel()) ? "" : Zs4GameData.getInstance().getPlayerLevel())
                .append("&channel=").append(Helper.isNull(Zs4GameData.getInstance().getChannel()) ? "" : Zs4GameData.getInstance().getChannel())
                .append("&sid=").append(getDeviceId())
                .append("&sid2=").append(getDeviceID2())
                .append("&mtype=").append(Build.MANUFACTURER)
                .append("&lang=").append(ProjectHelper.getLangString())
                .append("&mac=").append(ActivityHelper.getMacAddress())
                .append("&osver=").append(Build.VERSION.RELEASE)
                .append("&sdk_ver=").append(Extra.VERSION)
                .append("&ver=").append(ActivityHelper.getCurrentVersionName())
                .append("&loginkey=").append(Helper.isNull(Zs4GameData.getInstance().getLoginKey()) ? "" : Zs4GameData.getInstance().getLoginKey())
                .append("&system=").append("Android");
        return sb.toString();
    }

    /**
     * 取得user_agent1
     *
     * @return .append("").append()
     */
    public static String getUserAgent1(Context context) {


        ConnectivityManager connectionManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
        String timestamp = getTimestamp();
        StringBuilder sb = new StringBuilder()
                .append("app_id=").append(Zs4GameData.getInstance().getAppId())
                .append("&channel=").append(Zs4GameData.getInstance().getChannel())
                .append("&mac=").append(ActivityHelper.getMacAddress())
                .append("&sid=").append(getDeviceId())
                .append("&sid2=").append(getDeviceID2())
                .append("&sdk_ver=").append(Extra.VERSION)
                .append("&os_ver=").append(Build.VERSION.RELEASE)
                .append("&device_model=").append(android.os.Build.MODEL)
                .append("&device_type=").append(getDeviceType(context))
                .append("&lang=").append(ProjectHelper.getLangString())
                .append("&net=").append(null != networkInfo ? "wifi".equalsIgnoreCase(networkInfo.getTypeName()) ? "1" : "2" : "0")
                .append("&area_server_id=").append(Helper.isNotNull(Zs4GameData.getInstance().getServId()) ? Zs4GameData.getInstance().getServId() : "")
                .append("&area_server_name=").append(Helper.isNotNull(Zs4GameData.getInstance().getServName()) ? Zs4GameData.getInstance().getServName() : "")
                .append("&user_id=").append(Helper.isNotNull(Zs4GameData.getInstance().getUserId()) ? Zs4GameData.getInstance().getUserId() : "")
                .append("&role_id=").append(Helper.isNotNull(Zs4GameData.getInstance().getPlayerId()) ? Zs4GameData.getInstance().getPlayerId() : "")
                .append("&role_name=").append(Helper.isNotNull(Zs4GameData.getInstance().getPlayerName()) ? Zs4GameData.getInstance().getPlayerName() : "")
                .append("&role_level=").append(Helper.isNotNull(Zs4GameData.getInstance().getPlayerLevel()) ? Zs4GameData.getInstance().getPlayerLevel() : "")
                .append("&timestamp=").append(timestamp)
                .append("&safety=").append(MD5.md5(Zs4GameData.getInstance().getAppId() +
                        Zs4GameData.getInstance().getChannel() + ActivityHelper.getMacAddress() + getDeviceId() + timestamp + Zs4GameData.getInstance().getAppKey()));

        LogUtil.i("Zs4GameTD", "报道信息:  "+sb.toString());
        return JsonHelper.simpleEncode(sb.toString());
    }

    public static String getCurLang(Context context) {
        /**
         * 获得当前系统语言
         */
        Locale locale = context.getResources().getConfiguration().locale;
        String language = locale.getLanguage(); // 获得语言码
        return language;
    }

    public static String getDeviceId() {
        /**
         *新方法获取设备ID
         */
        DeviceUuidFactory deviceUuidFactory = new DeviceUuidFactory(ActivityHelper.getGlobalApplicationContext());
        String devicdId = deviceUuidFactory.getDeviceUuid().toString();
        if(Helper.isEmpty(devicdId)){
            devicdId = getDeviceID2();
        }
        return devicdId;
    }

    /**
     * 取得当前时间戳
     *
     * @return
     */
//    public static String getTimestamp() {
//        return date2String(new Date(), "yyyyMMddHHmmssSSS");
//    }
//
//    public static String date2String(Date date, String dateFormat) {
//        String dateStr = "";
//        try {
//            DateFormat df = new SimpleDateFormat(dateFormat);
//            dateStr = df.format(date);
//        } catch (Exception e) {
//            dateStr = "";
//        }
//        return System.currentTimeMillis()/1000L;
//    }

    /**
     * 取得当前时间戳
     *
     * @return
     */
    private static String getTimestamp() {
        return (System.currentTimeMillis() / 1000L)+"";
    }



    /**
     * 从url中取得指定参数名称的值
     *
     * @param url
     * @param paramName
     * @return
     */
    public static String getParamValueFromUrl(String url, String paramName) {
        String result = "";
        if (Helper.isNotEmpty(url) && Helper.isNotEmpty(paramName) && url.contains(paramName)) {
            String subUrl = url.substring(url.indexOf(paramName) + paramName.length() + 1);
            if (subUrl.contains("&")) {
                result = subUrl.substring(0, subUrl.indexOf('&'));
            } else {
                result = subUrl;
            }
        }
        return result;
    }


    /**
     * function: 得到请求版本参数
     *
     * @return
     * @ author: aXiBa 2013-3-28 下午5:34:45
     */
    public static ArrayList<NameValuePair> getUpdateVersionParame() {

        ArrayList<NameValuePair> paramsList = new ArrayList<NameValuePair>();

        paramsList.add(new BasicNameValuePair("v", Extra.VERSION_API));
        paramsList.add(new BasicNameValuePair("timestamp", PreferencesHelper.getInstance().getLong(Extra.Preferences.SDKGAME_KEY_LASTUPDATE_MENU, 1L) + ""));

        return paramsList;
    }


    /**
     * 取得统计时用的url数据
     *
     * @return
     */
    public static String getAdsData() {

        StringBuilder sb = new StringBuilder()
                .append("appid=").append(Zs4GameData.getInstance().getAppId())
                .append("&sid=").append(getDeviceId())
                .append("&mac=").append(ActivityHelper.getMacAddress())
                .append("&mtype=").append(Build.MANUFACTURER)
                .append("&os=").append(Build.VERSION.RELEASE)
                .append("&appver=").append(ActivityHelper.getCurrentVersionName())
                .append("&lan=").append(Locale.getDefault().getLanguage())
                .append("&crc=").append(1234)//与WEB约定的固定值，可以放在任意位置，用于判断解压后参数是否正确。
                ;
        return JsonHelper.simpleEncode(sb.toString());
    }


    /**
     * function: 得到橱窗广告请求参数
     *
     * @param adsId
     * @param width
     * @param height
     * @return
     * @ author: aXiBa 2013-3-14 下午3:20:03
     */
    public static ArrayList<NameValuePair> getWindowAdsParam2(String adsId, int width, int height) {

        ArrayList<NameValuePair> list = new ArrayList<NameValuePair>();

        list.add(new BasicNameValuePair("v", Extra.VERSION_API));
        list.add(new BasicNameValuePair("ad", adsId));
        list.add(new BasicNameValuePair("width", width + ""));
        list.add(new BasicNameValuePair("height", height + ""));
        list.add(new BasicNameValuePair("data", ParamsHelper.getAdsData()));
        list.add(new BasicNameValuePair("f", "1"));

        return list;
    }


    /**
     * function: 自动登录参数
     *
     * @return
     * @ author: aXiBa 2013-5-8 下午7:01:39
     */
    public static ArrayList<NameValuePair> getAutoLoginParam() {

        ArrayList<NameValuePair> list = new ArrayList<NameValuePair>();

        list.add(new BasicNameValuePair("v", Extra.VERSION_API));

        return list;
    }


    /**
     * function: 注销参数
     *
     * @param type
     * @return
     * @ author: aXiBa 2013-5-8 下午7:01:51
     */
    public static ArrayList<NameValuePair> getLogOutParam(String type) {

        ArrayList<NameValuePair> list = new ArrayList<NameValuePair>();

//        list.add(new BasicNameValuePair("v", Extra.VERSION_API));
        list.add(new BasicNameValuePair("type", type));

        return list;
    }


    /**
     * function: 角色记录参数
     *
     * @param playerid
     * @param playerName
     * @param serverId
     * @param serverName
     * @return
     * @ author: aXiBa 2013-5-13 上午11:19:09
     */
    public static ArrayList<NameValuePair> getUserInfoForPayParams(String playerid, String playerName, String serverId, String serverName,String playLevel) {

        ArrayList<NameValuePair> paramsList = new ArrayList<NameValuePair>();

        paramsList.add(new BasicNameValuePair("v", Extra.VERSION_API));
        paramsList.add(new BasicNameValuePair("appuserid", EncryptHelper.encodeByBase64(playerid)));
        paramsList.add(new BasicNameValuePair("appservercode", EncryptHelper.encodeByBase64(serverId)));
        paramsList.add(new BasicNameValuePair("appnickname", EncryptHelper.encodeByBase64(playerName)));
        paramsList.add(new BasicNameValuePair("appservername", EncryptHelper.encodeByBase64(serverName)));
        paramsList.add(new BasicNameValuePair("playgrade", EncryptHelper.encodeByBase64(playLevel)));

        return paramsList;
    }


    /**
     * function: 得到设备唯一号
     *
     * @return
     * @ author: aXiBa 2013-6-18 下午3:21:40
     */
    public static String getDeviceID2() {

        String deviceId = "";

        // 由设备硬件信息组成的序列号
        if (Helper.isEmpty(deviceId)) {
            deviceId = getUUID();
        }

        // 由设备硬件信息组成的序列号
        if (Helper.isEmpty(deviceId)) {
            deviceId = getDeviceSerialNumber();
        }

        // 设备序列号
        if (Helper.isEmpty(deviceId)) {
            deviceId = getSerialNumber();
        }

//		LogUtil.w(TAG, "deviceID: " + deviceId);
        return deviceId;
    }


    /**
     * function: 得到设备序列号
     *
     * @return
     * @ author: aXiBa 2012-11-21 下午4:14:04
     */
    public static String getSerialNumber() {
        String serial = null;
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class);
            serial = (String) get.invoke(c, "ro.serialno");
        } catch (Exception e) {

        }
        return serial;
    }


    /**
     * function: 由设备硬件信息组成的序列号
     *
     * @return
     * @ author: aXiBa 2012-11-21 下午4:15:38
     */
    public static String getDeviceSerialNumber() {

        return "35" + Build.BOARD.length() % 10 + Build.BRAND.length() % 10 + Build.CPU_ABI.length() % 10 +
                Build.DEVICE.length() % 10 + Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 +
                Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 + Build.MODEL.length() % 10 +
                Build.PRODUCT.length() % 10 + Build.TAGS.length() % 10 + Build.TYPE.length() % 10 +
                Build.USER.length() % 10;
    }

    /**
     * function: 得到手机开机时间
     *
     * @ author:ljp 2014-8-12 下午2:21:20
     */
    public static String getPhoneStartTime() {

        long time = SystemClock.elapsedRealtime();
        Date nowTime = new Date(System.currentTimeMillis() - time);
        SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        String retStrFormatNowDate = sdFormatter.format(nowTime);
//        LogUtil.e("开机时间：",retStrFormatNowDate.toString());
        return retStrFormatNowDate;
    }

    /**
     * function: 获取wlan mac地址
     *
     * @ author:ljp 2014-8-12 下午3:21:20
     */
    public static String getWifiMacAddress() {

        WifiManager wifi = (WifiManager) ActivityHelper.getGlobalApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        String wifiMac = info.getBSSID();

//		if(Helper.isEmpty(PreferencesHelper.getInstance(Extra.Preferences.SDKGAME_USERAGENT1_CONFIG).getString(Extra.DeviceInfoPreferences.WIFIADDR))){
//			PreferencesHelper.getInstance(Extra.Preferences.SDKGAME_USERAGENT1_CONFIG).putString(Extra.DeviceInfoPreferences.WIFIADDR, wifiMac);
//		}
        try {

            String inWifiaddr = EncryptHelper.decryptByRC4(FileUtils.readContent(FileUtils.getInternalFileDir().concat(Extra.FILE_UA_UL)));
            String exWifiaddr = "";
//            if (ActivityHelper.checkPermission_WRITE_EXTERNAL_STORAGE()) {
//                exWifiaddr = EncryptHelper.decryptByRC4(FileUtils.readContent(FileUtils.getSDCardRootDir().concat(Extra.PATH_SD_UL).concat(Extra.FILE_UA_UL)));
//                if (Helper.isEmpty(inWifiaddr) && Helper.isEmpty(exWifiaddr)) {
//                    String content = EncryptHelper.encryptByRC4(wifiMac);
//                    FileUtils.writeContent2File(content, FileUtils.getInternalFileDir(), Extra.FILE_UA_UL);
//                    FileUtils.writeContent2File(content, FileUtils.getSDCardRootDir().concat(Extra.PATH_SD_UL), Extra.FILE_UA_UL);
//                }
//            } else {
                if (Helper.isEmpty(inWifiaddr)) {
                    String content = EncryptHelper.encryptByRC4(wifiMac);
                    FileUtils.writeContent2File(content, FileUtils.getInternalFileDir(), Extra.FILE_UA_UL);

                }
//            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return wifiMac;

    }

    /**
     * function: 获取本地保存的wlan mac地址
     *
     * @ author:ljp 2014-8-12 下午3:41:20
     */
    public static String getLastWifiMacAddress() {
        String inWifiaddr = EncryptHelper.decryptByRC4(FileUtils.readContent(FileUtils.getInternalFileDir().concat(Extra.FILE_UA_UL)));
        String exWifiaddr = "";

//        if (ActivityHelper.checkPermission_WRITE_EXTERNAL_STORAGE()) {
//            exWifiaddr = EncryptHelper.decryptByRC4(FileUtils.readContent(FileUtils.getSDCardRootDir().concat(Extra.PATH_SD_UL).concat(Extra.FILE_UA_UL)));
//        }

        if (Helper.isNotEmpty(inWifiaddr)) {
            return inWifiaddr;
        } else if (Helper.isNotEmpty(exWifiaddr)) {
            return exWifiaddr;
        } else {
            return "";
        }
    }

    /**
     * function: 获取md5值：md5(mac+””+appid+uid+logintype+appkey)
     *
     * @ author:ljp 2015-3-12 下午3:41:20
     */
    public static String getMD5Code() {

        String md5CodeStr = ActivityHelper.getMacAddress() + Zs4GameData.getInstance().getAppId() + Zs4GameData.getInstance().getUserId() + Zs4GameData.getInstance().getLoginType() + Zs4GameData.getInstance().getAppKey();
        String md5Code = EncryptHelper.md5(md5CodeStr);
        return md5Code;
    }

    /**
     * function: 获取唯一标识
     *
     * @ author:ljp 2014-8-12 下午3:51:20
     */
    public static String getUUID() {

//		String uuid = PreferencesHelper.getInstance(Extra.Preferences.SDKGAME_USERAGENT1_CONFIG).getString(Extra.DeviceInfoPreferences.UUID, "");
//		if(Helper.isEmpty(uuid)){
//			uuid =  UUID.randomUUID().toString();
//			PreferencesHelper.getInstance(Extra.Preferences.SDKGAME_USERAGENT1_CONFIG).putString(Extra.DeviceInfoPreferences.UUID, uuid);
//		}

        String inUUID = EncryptHelper.decryptByRC4(FileUtils.readContent(FileUtils.getInternalFileDir().concat(Extra.FILE_UA_UUID_UL)));
        String exUUID = "";


//        if (ActivityHelper.checkPermission_WRITE_EXTERNAL_STORAGE()) {
//            exUUID = EncryptHelper.decryptByRC4(FileUtils.readContent(FileUtils.getSDCardRootDir().concat(Extra.PATH_SD_UL).concat(Extra.FILE_UA_UUID_UL)));
//            try {
//                if (Helper.isEmpty(inUUID) && Helper.isEmpty(exUUID)) {
//                    String uuid = UUID.randomUUID().toString();
//                    String content = EncryptHelper.encryptByRC4(uuid);
//                    FileUtils.writeContent2File(content, FileUtils.getInternalFileDir(), Extra.FILE_UA_UUID_UL);
//                    FileUtils.writeContent2File(content, FileUtils.getSDCardRootDir().concat(Extra.PATH_SD_UL), Extra.FILE_UA_UUID_UL);
//                    inUUID = uuid;
//                }
//
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//
//        } else {
            try {
                if (Helper.isEmpty(inUUID)) {
                    String uuid = UUID.randomUUID().toString();
                    String content = EncryptHelper.encryptByRC4(uuid);
                    FileUtils.writeContent2File(content, FileUtils.getInternalFileDir(), Extra.FILE_UA_UUID_UL);
                    inUUID = uuid;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
//        }

        if (Helper.isNotEmpty(inUUID)) {
            return inUUID;
        } else if (Helper.isNotEmpty(exUUID)) {
            return exUUID;
        } else {
            return "";
        }
    }

    public static String getDeviceType(Context context) {
        if (isTablet(context)) {
            return "2";
        } else {
            return "1";
        }
    }

    public static boolean isTablet(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }
}
